const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
    // 订单编号（自动生成）
    orderNumber: {
        type: String,
        required: true,
        unique: true
    },

    // 关联用户
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },

    // 关联车辆
    carId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Car',
        required: true
    },

    // 租赁时间
    startTime: {
        type: Date,
        required: true
    },
    endTime: {
        type: Date,
        required: true
    },

    // 取还车地点
    pickupLocation: {
        type: String,
        required: true
    },
    returnLocation: {
        type: String,
        required: true
    },

    // 订单状态
    status: {
        type: String,
        enum: ['进行中', '已完成', '已取消'],
        default: '进行中'
    },

    // 费用信息 - 直接从前端接收
    totalAmount: {
        type: Number,
        required: true,
        min: 0
    },
    rentalFee: {
        type: Number,
        required: true,
        min: 0
    },
    insuranceFee: {
        type: Number,
        default: 0
    },
    deposit: {
        type: Number,
        default: 0
    },

    // 简化附加服务
    additionalServices: [{
        type: String  // 只记录服务名称
    }],

    // 订单备注
    remarks: String,

    // 时间戳
    createdAt: {
        type: Date,
        default: Date.now
    },
    updatedAt: {
        type: Date,
        default: Date.now
    }
});

// 更新时自动更新时间
orderSchema.pre('save', function (next) {
    this.updatedAt = new Date();
    next();
});

// 生成订单编号的方法
orderSchema.pre('save', async function (next) {
    if (this.isNew) {
        const date = new Date();
        const timestamp = date.getTime().toString().slice(-8);
        const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        this.orderNumber = `ORDER${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}${timestamp}${random}`;
    }
    next();
});

// 计算租赁天数的虚拟字段
orderSchema.virtual('rentalDays').get(function () {
    return Math.ceil((this.endTime - this.startTime) / (1000 * 60 * 60 * 24));
});

// 设置 toJSON 选项
orderSchema.set('toJSON', { virtuals: true });
orderSchema.set('toObject', { virtuals: true });

// 修改导出为mongoose模型
module.exports = mongoose.model('Order', orderSchema); 